package p.ithorns.framework.feign.common;

import feign.RequestInterceptor;
import feign.codec.ErrorDecoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.UUID;

/**
 * FeignConfiguration
 *
 * @author Ht.L
 * @date 2024-03-27 15:41
 * @since 1.0.0
 */
@Configuration
public class FeignConfig {

    public final static String REQUEST_ID = "X-REQUEST-ID";

    /**
     * 给Feign设置请求头
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (null != attributes) {
                HttpServletRequest request = attributes.getRequest();

                // 传递所有请求头,防止部分丢失
                // 此处也可以只传递认证的header
                // requestTemplate.header("Authorization", request.getHeader("Authorization"));
                Enumeration<String> headerNames = request.getHeaderNames();
                while (headerNames.hasMoreElements()) {
                    String headName = headerNames.nextElement();
                    String header = request.getHeader(headName);
                    requestTemplate.header(headName, header);
                }

                // 微服务之间传递的唯一标识,区分大小写所以通过httpServletRequest获取
                if (request.getHeader(REQUEST_ID) == null) {
                    String sid = String.valueOf(UUID.randomUUID());
                    requestTemplate.header(REQUEST_ID, sid);
                }
            }
        };
    }

    /**
     * 自定义异常解码器
     *
     * @return OpenFeignErrorDecoder
     */
    @Bean
    public ErrorDecoder errorDecoder() {
        return new FeignErrorDecoder();
    }

}